<template>
	<div class="disease-management">
		<!-- 顶部操作栏 -->
		<div class="operation-bar">
			<div class="left-section">
				<el-button type="primary" icon="el-icon-plus" @click="handleAdd" size="medium" class="add-btn">
					新增疾病
				</el-button>
				<el-button type="success" icon="el-icon-refresh" @click="refreshData" :loading="loading" size="medium">
					刷新
				</el-button>
			</div>

			<div class="right-section">
				<el-input v-model="searchKeyword" placeholder="搜索疾病名称/编码" prefix-icon="el-icon-search"
					style="width: 200px; margin-right: 10px;" size="medium" clearable @input="handleSearch" />

				<el-select v-model="filter.diseaseType" placeholder="疾病分类" clearable style="width: 140px;" size="medium"
					@change="handleFilter">
					<el-option label="全部分类" value=""></el-option>
					<el-option v-for="type in diseaseTypes" :key="type" :label="type" :value="type" />
				</el-select>
			</div>
		</div>

		<!-- 疾病表格 -->
		<div class="disease-table-container">
			<el-table :data="filteredDiseaseList" v-loading="loading" style="width: 100%" border stripe
				:default-sort="{prop: 'diseaseCode', order: 'ascending'}" @sort-change="handleSortChange"
				class="disease-table">
				<el-table-column type="index" label="序号" width="70" align="center" />

				<el-table-column prop="diseaseCode" label="疾病编码" width="150" sortable align="center">
					<template slot-scope="{ row }">
						<span v-if="row.isEditing">
							<el-input v-model="row.editForm.diseaseCode" size="small" maxlength="20"
								class="edit-input" :disabled="true" />  <!-- 添加 :disabled="true" -->
						</span>
						<span v-else class="disease-code">
							<el-tag size="mini" type="info" effect="dark">{{ row.diseaseCode }}</el-tag>
						</span>
					</template>
				</el-table-column>

				<el-table-column prop="diseaseName" label="疾病名称" min-width="250" sortable>
					<template slot-scope="{ row }">
						<div v-if="row.isEditing" class="edit-cell">
							<el-input v-model="row.editForm.diseaseName" size="small" placeholder="请输入疾病名称"
								class="edit-input" />
						</div>
						<div v-else class="disease-info">
							<span class="disease-name">{{ row.diseaseName }}</span>
						</div>
					</template>
				</el-table-column>

				<el-table-column prop="diseaseType" label="疾病分类" width="200" sortable>
					<template slot-scope="{ row }">
						<div v-if="row.isEditing" class="edit-cell">
							<el-select v-model="row.editForm.diseaseType" size="small" class="edit-select"
								placeholder="选择疾病分类" style="width: 100%">
								<el-option v-for="type in diseaseTypes" :key="type" :label="type" :value="type" />
							</el-select>
						</div>
						<div v-else class="disease-type-info">
							<el-tag :type="getDiseaseTypeTag(row.diseaseType)" size="small">
								{{ row.diseaseType }}
							</el-tag>
						</div>
					</template>
				</el-table-column>

				<el-table-column label="操作" width="180" align="center" fixed="right">
					<template slot-scope="{ row }">
						<div class="action-buttons">
							<template v-if="row.isEditing">
								<el-button type="success" size="mini" icon="el-icon-check" @click="saveDisease(row)"
									:loading="row.saving" class="save-btn">
									保存
								</el-button>
								<el-button type="info" size="mini" icon="el-icon-close" @click="cancelEdit(row)"
									:disabled="row.saving">
									取消
								</el-button>
							</template>
							<template v-else>
								<el-button type="primary" size="mini" icon="el-icon-edit" @click="startEdit(row)"
									:disabled="editingRow && editingRow !== row" class="edit-btn">
									编辑
								</el-button>
								<el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteDisease(row)"
									class="delete-btn">
									删除
								</el-button>
							</template>
						</div>
					</template>
				</el-table-column>
			</el-table>

			<!-- 数据为空提示 -->
			<div v-if="!loading && filteredDiseaseList.length === 0" class="empty-tips">
				<el-empty description="暂无疾病数据" v-if="searchKeyword || filter.diseaseType">
					<el-button type="primary" @click="clearFilters">清除筛选条件</el-button>
				</el-empty>
				<el-empty description="暂无疾病数据，点击新增按钮添加" v-else>
					<el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增疾病</el-button>
				</el-empty>
			</div>
		</div>

		<!-- 新增/编辑疾病对话框 -->
		<el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @closed="handleDialogClosed"
			:close-on-click-modal="false">
			
			<el-form ref="diseaseForm" :model="formData" :rules="rules" label-width="80px" class="disease-form">
				<el-form-item label="疾病编码" prop="diseaseCode">
					<el-input v-model="formData.diseaseCode" placeholder="如：E11.900、I10.x00" maxlength="20"
						show-word-limit :disabled="isEditMode" />
				</el-form-item>

				<el-form-item label="疾病名称" prop="diseaseName">
					<el-input v-model="formData.diseaseName" placeholder="请输入疾病名称" maxlength="100" show-word-limit />
				</el-form-item>

				<el-form-item label="疾病分类" prop="diseaseType">
					<el-select v-model="formData.diseaseType" placeholder="请选择疾病分类" style="width: 100%" filterable
						allow-create>
						<el-option v-for="type in diseaseTypes" :key="type" :label="type" :value="type" />
					</el-select>
					<div class="form-tip">支持选择已有分类或输入新分类</div>
				</el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false" :disabled="submitting">
					取消
				</el-button>
				<el-button type="primary" @click="submitForm" :loading="submitting">
					确定
				</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import http from '../../utils/request'

	export default {
		name: 'DiseaseManagement',
		data() {
			// 验证疾病编码
			const validateDiseaseCode = (rule, value, callback) => {
				if (!value) {
					callback(new Error('疾病编码不能为空'))
					return
				}

				// 编码格式：字母数字点号组合
				const codePattern = /^[A-Za-z0-9\.]+$/
				if (!codePattern.test(value)) {
					callback(new Error('疾病编码只能包含字母、数字和点号'))
					return
				}

				// 检查编码是否重复（新增时检查）
				if (!this.isEditMode) {
					const exists = this.originalDiseaseList.some(disease => disease.diseaseCode === value)
					if (exists) {
						callback(new Error('该疾病编码已存在'))
						return
					}
				}

				callback()
			}

			return {
				// 数据
				originalDiseaseList: [],
				loading: false,

				// 搜索和筛选
				searchKeyword: '',
				filter: {
					diseaseType: ''
				},

				// 编辑状态
				editingRow: null,
				isEditMode: false,

				// 对话框相关
				dialogVisible: false,
				submitting: false,
				dialogTitle: '新增疾病',
				formData: {
					diseaseCode: '',
					diseaseName: '',
					diseaseType: ''
				},

				// 疾病分类列表（从数据中提取）
				diseaseTypes: [],

				// 表单验证规则
				rules: {
					diseaseCode: [{
						required: true,
						validator: validateDiseaseCode,
						trigger: 'blur'
					}],
					diseaseName: [{
							required: true,
							message: '请输入疾病名称',
							trigger: 'blur'
						},
						{
							min: 2,
							max: 100,
							message: '长度在 2 到 100 个字符',
							trigger: 'blur'
						}
					],
					diseaseType: [{
						required: true,
						message: '请选择疾病分类',
						trigger: 'change'
					}]
				}
			}
		},

		computed: {
			// 计算过滤后的疾病列表
			filteredDiseaseList() {
				let list = this.originalDiseaseList

				// 关键词搜索
				if (this.searchKeyword) {
					const keyword = this.searchKeyword.toLowerCase()
					list = list.filter(item =>
						item.diseaseName.toLowerCase().includes(keyword) ||
						item.diseaseCode.toLowerCase().includes(keyword)
					)
				}

				// 分类筛选
				if (this.filter.diseaseType) {
					list = list.filter(item => item.diseaseType === this.filter.diseaseType)
				}

				return list
			}
		},

		async created() {
			await this.loadDiseaseData()
		},

		methods: {
			// 加载疾病数据
			async loadDiseaseData() {
				this.loading = true
				try {
					const resp = await http.get('/admin/getDiseaseList')
					if (resp.data.code === 1) {
						this.originalDiseaseList = resp.data.data.map(item => ({
							diseaseCode: item.diseaseCode,
							diseaseName: item.diseaseName,
							diseaseType: item.diseaseType,
							// 编辑状态
							isEditing: false,
							saving: false,
							editForm: {}
						}))

						// 提取疾病分类列表
						this.extractDiseaseTypes()

						// 按疾病编码排序
						this.originalDiseaseList.sort((a, b) => a.diseaseCode.localeCompare(b.diseaseCode))
					} else {
						this.$message.error(resp.data.msg || '获取疾病列表失败')
					}
				} catch (error) {
					this.$message.error('网络请求失败')
					console.error('加载疾病数据失败:', error)
				} finally {
					this.loading = false
				}
			},

			// 提取疾病分类列表
			extractDiseaseTypes() {
				const types = new Set()
				this.originalDiseaseList.forEach(item => {
					if (item.diseaseType) {
						types.add(item.diseaseType)
					}
				})
				this.diseaseTypes = Array.from(types).sort()
			},

			// 刷新数据
			refreshData() {
				this.searchKeyword = ''
				this.filter.diseaseType = ''
				this.loadDiseaseData()
			},

			// 搜索
			handleSearch() {
				// 实时搜索，无需额外处理
			},

			// 筛选
			handleFilter() {
				// 实时筛选，无需额外处理
			},

			// 清除筛选条件
			clearFilters() {
				this.searchKeyword = ''
				this.filter.diseaseType = ''
			},

			// 排序改变
			handleSortChange({
				prop,
				order
			}) {
				this.originalDiseaseList.sort((a, b) => {
					let aValue = a[prop]
					let bValue = b[prop]

					if (typeof aValue === 'string') {
						aValue = aValue.toLowerCase()
						bValue = bValue.toLowerCase()
					}

					if (aValue < bValue) {
						return order === 'ascending' ? -1 : 1
					}
					if (aValue > bValue) {
						return order === 'ascending' ? 1 : -1
					}
					return 0
				})
			},

			// 开始编辑
			startEdit(row) {
				// 确保同一时间只有一个在编辑
				if (this.editingRow && this.editingRow !== row) {
					this.$message.warning('请先完成当前编辑')
					return
				}

				this.cancelEdit(this.editingRow)

				row.isEditing = true
				row.editForm = {
					...row
				}
				this.editingRow = row
				this.isEditMode = true
			},

			// 保存编辑
			async saveDisease(row) {
				try {
					// 验证必填字段
					if (!row.editForm.diseaseName || !row.editForm.diseaseName.trim()) {
						this.$message.error('疾病名称不能为空')
						return
					}

					if (!row.editForm.diseaseType) {
						this.$message.error('疾病分类不能为空')
						return
					}

					row.saving = true

					const response = await http.post('/admin/updateDisease', {
						diseaseCode: row.diseaseCode,
						diseaseName: row.editForm.diseaseName,
						diseaseType: row.editForm.diseaseType
					})

					if (response.data.code === 1) {
						this.$message.success('保存成功')

						// 更新本地数据
						Object.assign(row, row.editForm)
						row.isEditing = false
						row.saving = false
						this.editingRow = null
						this.isEditMode = false

						// 更新疾病分类列表
						this.extractDiseaseTypes()
					} else {
						this.$message.error(response.data.msg || '保存失败')
						row.saving = false
					}
				} catch (error) {
					this.$message.error('保存失败')
					row.saving = false
					console.error('保存疾病信息失败:', error)
				}
			},

			// 取消编辑
			cancelEdit(row) {
				if (row) {
					row.isEditing = false
					row.saving = false
					row.editForm = {
						...row
					}
				}
				this.editingRow = null
				this.isEditMode = false
			},

			// 删除疾病
			deleteDisease(row) {
				this.$confirm(`确定要删除疾病【${row.diseaseName}】吗？`, '删除确认', {
					type: 'warning',
					confirmButtonText: '确定删除',
					cancelButtonText: '取消',
					confirmButtonClass: 'el-button--danger',
					center: true
				}).then(async () => {
					try {
						const response = await http.post('/admin/deleteDisease', {
							diseaseCode: row.diseaseCode
						})

						if (response.data.code === 1) {
							this.$message.success('删除成功')

							// 从列表中移除
							const index = this.originalDiseaseList.findIndex(item => item.diseaseCode === row
								.diseaseCode)
							if (index !== -1) {
								this.originalDiseaseList.splice(index, 1)
								this.extractDiseaseTypes()
							}
						} else {
							this.$message.error(response.data.msg || '删除失败')
						}
					} catch (error) {
						this.$message.error('删除失败')
						console.error('删除疾病失败:', error)
					}
				}).catch(() => {
					// 用户取消删除
				})
			},

			// 新增疾病
			handleAdd() {
				this.cancelEdit(this.editingRow)
				this.isEditMode = false
				this.dialogTitle = '新增疾病'
				this.formData = {
					diseaseCode: '',
					diseaseName: '',
					diseaseType: this.diseaseTypes[0] || ''
				}
				this.dialogVisible = true
			},

			// 提交表单（新增）
			submitForm() {
				this.$refs.diseaseForm.validate(async (valid) => {
					if (!valid) return

					this.submitting = true

					try {
						const response = await http.post('/admin/addDisease', this.formData)

						if (response.data.code === 1) {
							this.$message.success('新增成功')
							this.dialogVisible = false
							await this.loadDiseaseData()
						} else {
							this.$message.error(response.data.msg || '新增失败')
						}
					} catch (error) {
						this.$message.error('新增失败')
						console.error('新增疾病失败:', error)
					} finally {
						this.submitting = false
					}
				})
			},

			// 对话框关闭
			handleDialogClosed() {
				this.$refs.diseaseForm?.resetFields()
				this.submitting = false
			},

			// 获取疾病分类标签样式
			getDiseaseTypeTag(type) {
				const typeMap = {
					'内分泌疾病': 'success',
					'循环系统疾病': 'danger',
					'呼吸系统疾病': 'primary',
					'消化系统疾病': 'warning',
					'神经系统疾病': 'info',
					'泌尿系统疾病': 'success',
					'血液系统疾病': 'danger',
					'免疫系统疾病': 'primary'
				}
				return typeMap[type] || 'info'
			}
		}
	}
</script>

<style scoped>
	.disease-management {
		padding: 20px;
		background: #f0f2f5;
		min-height: calc(100vh - 60px);
	}

	.operation-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
		padding: 20px;
		background: white;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
	}

	.left-section {
		display: flex;
		gap: 10px;
	}

	.right-section {
		display: flex;
		align-items: center;
	}

	.add-btn {
		background: linear-gradient(135deg, #409EFF 0%, #337ecc 100%);
		border: none;
	}

	.disease-table-container {
		background: white;
		border-radius: 8px;
		padding: 20px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
		margin-bottom: 20px;
		min-height: 400px;
	}

	.disease-table {
		border-radius: 6px;
		overflow: hidden;
	}

	.disease-table :deep(.el-table__header-wrapper) {
		background: #fafafa;
	}

	.disease-table :deep(.el-table__body tr:hover) {
		background-color: #f5f7fa !important;
	}

	.disease-info {
		display: flex;
		align-items: center;
	}

	.disease-name {
		font-weight: 500;
		color: #303133;
	}

	.disease-type-info {
		display: flex;
		align-items: center;
	}

	.disease-code {
		font-family: 'Consolas', monospace;
		font-weight: 600;
		color: #409EFF;
	}

	.action-buttons {
		display: flex;
		gap: 6px;
		justify-content: center;
	}

	.edit-input,
	.edit-select {
		width: 100%;
	}

	.empty-tips {
		padding: 40px 0;
		text-align: center;
	}

	.form-tip {
		font-size: 12px;
		color: #909399;
		margin-top: 5px;
	}

	.dialog-footer {
		text-align: right;
		padding-top: 20px;
		border-top: 1px solid #ebeef5;
	}

	:deep(.el-table__row) {
		transition: all 0.3s ease;
	}

	:deep(.el-table__row.is-editing) {
		background-color: #f0f9ff !important;
	}

	:deep(.el-table__row.is-editing:hover) {
		background-color: #e6f7ff !important;
	}

	:deep(.el-table__row .el-input__inner) {
		border-radius: 4px;
	}

	:deep(.el-table__row .el-select .el-input__inner) {
		border-radius: 4px;
	}
</style>		